package com.atguigu.gmall.product.service.impl;

import com.atguigu.gmall.common.util.DateUtil;
import com.atguigu.gmall.common.config.minio.propertie.MinioProperties;
import com.atguigu.gmall.product.service.FileService;
import io.minio.MinioClient;
import io.minio.PutObjectOptions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.util.Date;
import java.util.UUID;

@Service
public class FileServiceImpl implements FileService {

    @Autowired
    MinioProperties minioProperties;
    @Autowired
    MinioClient client;

    @Override
    public String fileUpload(MultipartFile file) throws Exception {

/*        //1创建minio客户端
        MinioClient client = new MinioClient(
                minioProperties.getEndpoint(),//http://192.168.200.100:9000 是API连接地址  http://192.168.200.100:9001是访问管理地址
                minioProperties.getAccessKey(),
                minioProperties.getSecretKey());
        //2查看桶是否存在
        if (!client.bucketExists(minioProperties.getBucketName())) {
            client.makeBucket(minioProperties.getBucketName());
        }*/

        //3上传文件到桶里
        InputStream stream = file.getInputStream();
        //文件名进行优化
        String date = DateUtil.formatDate(new Date());
        String filename = date+ "/" +UUID.randomUUID()+ "_" +file.getOriginalFilename();

        String contentType = file.getContentType();
        PutObjectOptions options = new PutObjectOptions(file.getSize(), -1L);//文件上传设置
        options.setContentType(contentType);

        client.putObject(minioProperties.getBucketName(), filename, stream, options);

        //返回文件的url地址
        String url = minioProperties.getEndpoint()+"/"+minioProperties.getBucketName()+"/"+filename;
        return url;
    }
}
